package io.terminus.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import io.terminus.spzx.consts.UserInfoConstant;
import io.terminus.spzx.model.entity.system.SysUser;
import io.terminus.spzx.model.vo.common.Result;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpOptions;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 登录验证自定义拦截器
 * @Date 2024-04-13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginAuthInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 1、获取请求方式: 如果请求方式是OPTIONS预检请求，就直接放行
        if (HttpOptions.METHOD_NAME.equals(request.getMethod())) {
            return true;
        }

        // 2、从请求头获取token
        String token = request.getHeader(UserInfoConstant.USERINFO_TOKEN_REQUEST_HEADER);

        // 3-1、如果token为空，返回错误提示
        if (StrUtil.isEmpty(token)) {
            responseNotLoginInfo(response);
            return false;
        }

        // 3-2、如果token不为空，拿着token查询redis
        String userInfo = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + token);

        // 4-1、如果redis查询不到数据，返回错误提示
        if (StrUtil.isEmpty(userInfo)) {
            responseNotLoginInfo(response);
            return false;
        }

        // 4-2、如果redis查询到用户信息，把用户信息放到ThreadLocal里面
        SysUser sysUser = JSON.parseObject(userInfo, SysUser.class);
        AuthContextUtil.set(sysUser);

        // 4-3、更新Redis用户信息数据的过期时间
        redisTemplate.expire(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + token, 30, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        // 清空ThreadLocal中的数据，防止内存泄漏
        AuthContextUtil.remove();
    }

    /**
     * 响应208状态码给前端
     *
     * @param response 响应对象
     */
    private void responseNotLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("responseNoLoginInfo, except info={}", Throwables.getStackTraceAsString(e));
        }
    }
}
